package com.fmatos.amazingwallpapers.image;


import javax.inject.Inject;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.util.Log;

/**
 * Provides the same interface of the cloud manager,
 * but handles network and heavy tasks in another thread 
 * as to make everything zippier
 * 
 * @author fdematos
 *
 */
public class AsyncCloudManager  {

	// TODO make a thread pool
	private static final String TAG = AsyncCloudManager.class.getSimpleName();

	private CloudManager cloudManager;
	@Inject Activity activity;

	@Inject
	public AsyncCloudManager(Context context,CloudManager cloudManager) {
//		cloudManager = new CloudManager(context);
		this.cloudManager = cloudManager;
	}
	
	public void refreshAlbumInfo(final String albumName, final Runnable runnableForUiThread) {
		Log.i(TAG,"Intercept refresh album and launch another thread");
		
		Thread thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				Log.i(TAG,"start thread for refresh album and launch another thread");
				if ( albumName != null ) {
					cloudManager.refreshAlbumInfo(albumName);
				}
				
				runUiOnThread(runnableForUiThread);
			}
		});
		
		thread.start();	
	}

	/**
	 * Gets fresh list of albums from server and gets newest urls for all albums
	 * @param runnableForUiThread
	 */
	public void refreshAlbumList(final Runnable runnableForUiThread) {
		Log.i(TAG,"Intercept refresh all albums and launch another thread");
		
		Thread thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				Log.i(TAG,"start thread for refresh all albums and launch another thread");

				cloudManager.refreshAlbumList();

				runUiOnThread(runnableForUiThread);
			}
			
			
		});
		
		thread.start();
		
	}
	
	public void getPhotoFromNetwork(final String thumbnailUrl,final Runnable runnableForUiThread) {
		Thread thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				
				if ( thumbnailUrl != null ) {
					cloudManager.getPhotoFromNetwork(thumbnailUrl);
					runUiOnThread(runnableForUiThread);
				}
			}
		});
		
		thread.start();
		
	}


	private void runUiOnThread(Runnable runnableForUiThread) {

		if ( activity != null && runnableForUiThread != null ) {
			Log.d(TAG,"Running callback on UI thread");
			activity.runOnUiThread(runnableForUiThread);
		} else {
			Log.d(TAG,"No runnable on UI thread or no activity available");
		}
		
	}
}
